package leetCode.offer32_ii;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Solution2 implements Solution {

    @Override
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null){
            return result;
        }
        // 第一层
        List<TreeNode> treeNodes = new ArrayList<>();
        treeNodes.add(root);
        nextTreeNode(treeNodes,result);
        return result;
    }

    List<TreeNode> nextTreeNode(List<TreeNode> treeNodes,List<List<Integer>> result) {
        if (treeNodes.size() == 0){
            return null;
        }
        List<TreeNode> nextTreeNode = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        treeNodes.forEach(e -> {
            list.add(e.val);
            if (e.left != null){
                nextTreeNode.add(e.left);
            }
            if (e.right != null){
                nextTreeNode.add(e.right);
            }
        });
        result.add(list);
        return nextTreeNode(nextTreeNode,result);
    }

}
